$(function() {
    withLibrary('jUrl', function() {
	withLibrary('jBbq', function() {
	    $(window).bind('hashchange', function(e) {
		PANIM.pageChanged(e);
		PAGE_HOOKS.pageLoaded(e.fragment);
	    });
	});
    });
    replaceHrefs(this);
});

function replaceHrefs(context) {
    $(context).find('a').each(function() {
	$(this).attr('href', '#' + $(this).attr('href').substr(1));
    });
}

var PANIM = {
    fragment: null,
    getUrl: function() {
	return '/pageContent/' + this.fragment;
    },
    cache: {
	//		    '': $('.index')
    },
    pageChanged: function(e) {
	this.fragment = e.fragment;
	if (this.fragment == "") {
	    this.fragment = "index.html";
	}
	if (typeof SLIDESHOW != 'undefined') {
	    if (this.fragment == "" || this.fragment == "index.html") {
		SLIDESHOW.start();
	    }
	    else {
		SLIDESHOW.stop();
	    }
	}
	var visible = $('.contentCell:visible');
	
	this.getNewPage(this.getUrl());
	visible.css({
	    "position": "absolute"
	}).fadeOut(500, function() {
	    PANIM.showLoader();
	});

	
    },
    loaderCount: 0,
    showLoader: function() {
	if (PANIM.loaderCount == 0) { $("#loader").fadeIn(500)};
	PANIM.loaderCount++;
    },
    hideLoader: function() {
	PANIM.loaderCount--;
	$("#loader").fadeOut(500);
    },
    displayNewContent: function(content) {
	PANIM.hideLoader();

	content.css({
	    "display": "none",
	    "top" : 0,
	    'left' : 0
	});
	content.fadeIn(1000);
	$("#cellHolder").height(content.height());
    },
    getNewPage: function(url) {
	if (!PANIM.cache[url]) {
	    $("#cellHolder").height(500);
	    // Create container for this url's content and store a reference to it in
	    // the cache.
	    PANIM.cache[url] = $('<div class="contentCell"/>')
		.appendTo('#cellHolder')
		.css({"width": "100%"})
		.load(url, function() {
		    // Content loaded, hide "loading" content.
		    replaceHrefs("#cellHolder");

		    PANIM.displayNewContent(PANIM.cache[url]);
		    _gaq.push([ '_trackPageview', PANIM.fragment]);
		});
	}
	else {
	    PANIM.displayNewContent(PANIM.cache[url]);
	}
	return PANIM.cache[url];
    }
    
}
